package com.gee.spring.cloud.data.transform.core.center.config.handler;

import cn.hutool.core.util.HexUtil;
import com.gee.spring.cloud.common.core.api.result.ApiResult;
import com.gee.spring.cloud.common.core.entity.center.config.Satellite;
import com.gee.spring.cloud.common.starter.config.event.CenterConfigEventHandler;
import com.gee.spring.cloud.common.starter.feign.center.config.SatelliteClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gepengjun
 * @since 2024/3/19 14:38
 */
@Component
public class SatelliteHandler extends CenterConfigEventHandler<Satellite> {

    private final ConcurrentHashMap<Long, Satellite> SATELLITE_MAP = new ConcurrentHashMap<>();

    @Autowired
    private SatelliteClient satelliteClient;

    public Satellite getById(Long id){
        return SATELLITE_MAP.computeIfAbsent(id, sateId -> satelliteClient.getById(sateId).getData());
    }

    @Override
    public void handlerUpdate(List<Satellite> dataList, List<Satellite> oldList) {
        dataList.forEach(satellite -> SATELLITE_MAP.computeIfPresent(satellite.getId(), (id, old) -> satellite));
    }

    @Override
    public void handlerDelete(List<Satellite> oldList) {
        oldList.forEach(satellite -> SATELLITE_MAP.remove(satellite.getId()));
    }

    public Satellite getBySateIdentity(long sateIdentity) {
        Optional<Satellite> satelliteOptional = SATELLITE_MAP.values().stream()
                .filter(satellite ->sateIdentity == satellite.getSateIdentity())
                .findFirst();
        if (satelliteOptional.isPresent()){
            return satelliteOptional.get();
        }else {
            ApiResult<Satellite> satelliteApiResult = satelliteClient.getBySateIdentity(sateIdentity);
            Satellite satellite = satelliteApiResult.getData();
            if (satelliteApiResult.isSuccess() && satellite != null){
                SATELLITE_MAP.put(satellite.getId(), satellite);
            }else {
                throw new RuntimeException("根据卫星标识["+ HexUtil.toHex(sateIdentity)+"]未获取到卫星 ");
            }
            return satellite;
        }
    }
}
